package com.music.peacerhythms.active;


import static com.music.peacerhythms.Uakj.UaMeth.format;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.media.metrics.Event;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SearchEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.SeekBar;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.music.peacerhythms.R;
import com.music.peacerhythms.Uakj.Constants;
import com.music.peacerhythms.Uakj.MusicDataBase;
import com.music.peacerhythms.Uakj.MusicOperation;
import com.music.peacerhythms.Uakj.MyEvent;
import com.music.peacerhythms.Uakj.PlayEvent;
import com.music.peacerhythms.Uakj.SoundPoolManager;
import com.music.peacerhythms.Uakj.UaMeth;

import com.music.peacerhythms.databinding.ActivityConfigBinding;
import com.music.peacerhythms.info.MusicInfo;
import com.music.peacerhythms.widget.WidgetProvider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConfigActivity extends AppCompatActivity implements View.OnClickListener {


    ActivityConfigBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityConfigBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initOnclick();
        initMusic();
        initMusicNew();

        add();
        EventBus.getDefault().register(this);
    }


    Chronometer chronometer;

    void startTime(long minu) {

        chronometer = binding.time;
        chronometer.setBase(minu + System.currentTimeMillis());

        int hour = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000 / 60);
        if (hour > 0) binding.time.setFormat("0" + String.valueOf(hour) + ":%s");
        chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                long base = chronometer.getBase();
                long cur1 = System.currentTimeMillis();

                long l = base - cur1;
                if (l <= 0) {
                    chronometer.stop();
                    SoundPoolManager.getAppManager().autoPause();
                    binding.time.setText("00:00:00");
                    binding.play.setImageResource(R.mipmap.play);
                } else {
                    chronometer.setText(format(l));
                }
            }
        });
        chronometer.start();
    }


    private void initOnclick() {
        binding.tvconfig.setOnClickListener(this);
        binding.night.setOnClickListener(this);
        binding.time.setOnClickListener(this);
        binding.gomusicset.setOnClickListener(this);
        binding.play.setOnClickListener(this);
        binding.rain.setOnClickListener(this);
    }

    private void initMusicNew() {


    }




    private MusicOperation musicOperation;

    private void initMusic() {
        int screenBrightness = UaMeth.getScreenBrightness(this);

        binding.tvlight.setText(screenBrightness*100/255 + "%");

        musicOperation = (MusicOperation) MusicDataBase.getInstance(this).musicOperation();
        if (musicOperation.initAllMusic().size() == 0) {
            MusicInfo info = new MusicInfo(R.mipmap.rain_con, R.raw.rain, "Rain", 0.5f, true, false, "");
            MusicInfo info2 = new MusicInfo(R.mipmap.ocean, R.raw.ocean, "Ocean", 0.5f, true, false, "");
            MusicInfo info3 = new MusicInfo(R.mipmap.stream, R.raw.stream, "Stream", 0.5f, true, false, "");
            MusicInfo info4 = new MusicInfo(R.mipmap.drip, R.raw.rain, "Drip", 0.5f, false, false, "https://peacexv.s3.ap-south-1.amazonaws.com/garen/drip.mp3");
            MusicInfo info5 = new MusicInfo(R.mipmap.wind, R.raw.rain, "Wind", 0.5f, false, false, "https://peacexv.s3.ap-south-1.amazonaws.com/garen/wind.wav");
            MusicInfo info6 = new MusicInfo(R.mipmap.foreat, R.raw.rain, "Forest", 0.5f, false, false, "https://peacexv.s3.ap-south-1.amazonaws.com/garen/forest.wav");
            MusicInfo info7 = new MusicInfo(R.mipmap.animals, R.raw.rain, "Animals", 0.5f, false, false, "https://peacexv.s3.ap-south-1.amazonaws.com/garen/animals.wav");
            MusicInfo info8 = new MusicInfo(R.mipmap.fire, R.raw.rain, "Fire", 0.5f, false, false, "https://peacexv.s3.ap-south-1.amazonaws.com/garen/fire.wav");
            MusicInfo info9 = new MusicInfo(R.mipmap.clock, R.raw.rain, "Clock", 0.5f, false, false, " https://peacexv.s3.ap-south-1.amazonaws.com/garen/clock.wav");
            musicOperation.addData(info);
            musicOperation.addData(info2);
            musicOperation.addData(info3);
            musicOperation.addData(info4);
            musicOperation.addData(info5);
            musicOperation.addData(info6);
            musicOperation.addData(info7);
            musicOperation.addData(info8);
            musicOperation.addData(info9);
        }


    }

    private void sendNotify() {
        try {
            Intent intent2 = new Intent();
            intent2.setClass(this, WidgetProvider.class);
            intent2.addCategory(Constants.ACTION_PLAY);
            intent2.setAction(Constants.ACTION_PLAY);
            intent2.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            int[] idss = AppWidgetManager.getInstance(this).getAppWidgetIds(new ComponentName(this, WidgetProvider.class));
            intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, idss);
            sendBroadcast(intent2);


        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private void sendNotifystop() {
        try {
            Intent intent2 = new Intent();
            intent2.setClass(this, WidgetProvider.class);
            intent2.addCategory(Constants.ACTION_STOP);
            intent2.setAction(Constants.ACTION_STOP);
            intent2.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            int[] idss = AppWidgetManager.getInstance(this).getAppWidgetIds(new ComponentName(this, WidgetProvider.class));
            intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, idss);
            sendBroadcast(intent2);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    void add() {



/*        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            AppWidgetManager mAppWidgetManager = getSystemService(AppWidgetManager.class);

            ComponentName myProvider = new ComponentName(ConfigActivity.this, WidgetProvider.class);

            Bundle b = new Bundle();
            b.putString("ggg", "ggg");
            if (mAppWidgetManager.isRequestPinAppWidgetSupported()) {
                try {
                    Intent pinnedWidgetCallbackIntent = new Intent(ConfigActivity.this, WidgetProvider.class);
                    PendingIntent successCallback;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
                        successCallback = PendingIntent.getBroadcast(ConfigActivity.this, 0, pinnedWidgetCallbackIntent, PendingIntent.FLAG_IMMUTABLE);
                    } else {
                        successCallback = PendingIntent.getBroadcast(ConfigActivity.this, 0, pinnedWidgetCallbackIntent, PendingIntent.FLAG_IMMUTABLE);
                    }

                    mAppWidgetManager.requestPinAppWidget(myProvider, b, successCallback);
                } catch (Exception e) {
                    Log.e("aaaa", e.toString());
                }
            }
        }*/


    }

    public static Long getLongFromString(String dateTime) {
        String[] split = dateTime.split(":");
        long time;
        if (split.length > 2) {
            time = ((Integer.parseInt(split[0]) * 60 * 60 + Integer.parseInt(split[1]) * 60 + Integer.parseInt(split[2])) * 1000);
        } else {
            time = (Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1])) * 1000;
        }
        return time;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MyEvent event) {
        SoundPoolManager.getAppManager().play(event.checkmusicInfos, this);

        int brightness = event.checkmusicInfos.get(0).Brightness;
        binding.tvlight.setText(brightness + "%");
        UaMeth.setAppScreenBrightness(brightness *255 / 100  , this);
        if (event.checkmusicInfos.size() > 1) {

            binding.rain.setImageResource(R.mipmap.sound);
            binding.tvsound.setText(event.checkmusicInfos.get(0).configname);
        } else {
            binding.tvsound.setText(event.checkmusicInfos.get(0).musicname);
            switch (event.checkmusicInfos.get(0).musicid) {
                case 1:
                    binding.rain.setImageResource(R.mipmap.rain_home);
                    break;
                case 2:
                    binding.rain.setImageResource(R.mipmap.ocean_home);
                    break;
                case 3:
                    binding.rain.setImageResource(R.mipmap.stream_home);
                    break;
                case 4:
                    binding.rain.setImageResource(R.mipmap.drip_home);
                    break;
                case 5:
                    binding.rain.setImageResource(R.mipmap.wind_home);
                    break;
                case 6:
                    binding.rain.setImageResource(R.mipmap.forest_home);
                    break;
                case 7:
                    binding.rain.setImageResource(R.mipmap.animals_home);
                    break;
                case 8:
                    binding.rain.setImageResource(R.mipmap.forest_home);
                    break;
                case 9:
                    binding.rain.setImageResource(R.mipmap.clock_home);
                    break;
            }

        }

        isplaying = true;
        binding.play.setImageResource(R.mipmap.suspend);
        startTime(getLongFromString(binding.time.getText().toString()));

        sendNotify();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PlayEvent event) {
        if (event.isplay) {
            binding.play.setImageResource(R.mipmap.play);
        } else {
            binding.play.setImageResource(R.mipmap.suspend);
        }


    }

    ArrayList<ArrayList<MusicInfo>> allconfig;

    @Override
    protected void onResume() {
        super.onResume();
        allconfig = UaMeth.getAllconfig(this);
        if (allconfig.size() > 0)
            binding.tvconfig.setText(allconfig.get(0).get(0).configname + ">");
        else binding.tvconfig.setText("");


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sendNotifystop();

        SoundPoolManager.getAppManager().destroy();
        EventBus.getDefault().unregister(this);
    }

    private PendingIntent getPlayPendingIntent(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, WidgetProvider.class);
        intent.addCategory(Constants.ACTION_PLAY);
        intent.setAction(Constants.ACTION_PLAY);
        PendingIntent pi;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        }
        return pi;
    }







    private boolean isplaying;

    @Override
    public void onClick(View v) {
        int id = v.getId();
        Intent intent;
        switch (id) {
            case R.id.time:
                showtimePopwindow();
                break;
            case R.id.rain:
            case R.id.night:
                intent = new Intent(ConfigActivity.this, AddConfigActivity.class);

                startActivity(intent);
                break;
            case R.id.gomusicset:
                intent = new Intent(ConfigActivity.this, PeaceSettingActivity.class);

                startActivity(intent);
                break;
            case R.id.tvconfig:
                showconfigPopwindow();
                break;
            case R.id.play:
                if (isplaying) {
                    chronometer.stop();
                    binding.play.setImageResource(R.mipmap.play);
                    SoundPoolManager.getAppManager().autoPause();
                    sendNotifystop();
                } else {
                    sendNotify();


                    startTime(getLongFromString(binding.time.getText().toString()));
                    binding.play.setImageResource(R.mipmap.suspend);
                    if (SoundPoolManager.soundmap.size() == 0) {
                        List<MusicInfo> musicInfos = musicOperation.initAllMusic();
                        musicInfos.get(0).isSelect = true;
                        musicInfos.get(0).volume = 0.3f;
                        List<MusicInfo> musicInfoss = new ArrayList<>();
                        musicInfoss.add(musicInfos.get(0));
                        SoundPoolManager.getAppManager().play(musicInfoss, ConfigActivity.this);
                    } else {

                    }
                    SoundPoolManager.getAppManager().autoResume();
                }
                isplaying = !isplaying;
                break;
        }
    }


    int minutes = 30;

    private void showtimePopwindow() {

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popwindow_time, null);

        final PopupWindow window = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        window.setFocusable(true);
        NumberPicker mPicker = view.findViewById(R.id.activity_main_numberpicker);
        mPicker.setDisplayedValues(new String[]{"15 minutes", "20 minutes", "30 minutes", "45 minutes", "60 minutes", "90 minutes", "120 minutes"});
        mPicker.setMinValue(0);
        mPicker.setMaxValue(6);
        mPicker.setValue(1);

        mPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

            }
        });


        view.findViewById(R.id.canc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
            }
        });
        view.findViewById(R.id.conf).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
                int value = mPicker.getValue();
                switch (value) {
                    case 0:
                        minutes = 15;
                        break;
                    case 1:
                        minutes = 20;
                        break;
                    case 2:
                        minutes = 30;
                        break;
                    case 3:
                        minutes = 45;
                        break;
                    case 4:
                        minutes = 60;
                        break;
                    case 5:
                        minutes = 90;
                        break;
                    case 6:
                        minutes = 120;
                        break;
                }
                chronometer.stop();
                if (value != 6 && value != 5) binding.time.setText(minutes + ":00");
                else if (value == 5) binding.time.setText(01 + ":" + 30 + ":00");
                else if (value == 6) binding.time.setText(02 + ":" + "00" + ":00");
            }
        });

        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);


        window.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {


            }
        });
        window.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void showconfigPopwindow() {

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popwindow_time, null);

        final PopupWindow window = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        window.setFocusable(true);
        NumberPicker mPicker = view.findViewById(R.id.activity_main_numberpicker);
        String[] strings = new String[allconfig.size()];
        for (int i = 0; i < allconfig.size(); i++) {
            strings[i] = allconfig.get(i).get(0).configname;
        }

        mPicker.setDisplayedValues(strings);
        mPicker.setMinValue(0);
        mPicker.setMaxValue(strings.length - 1);
        mPicker.setValue(0);

        mPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

            }
        });


        view.findViewById(R.id.canc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
            }
        });
        view.findViewById(R.id.conf).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
                int value = mPicker.getValue();
                EventBus.getDefault().post(new MyEvent(allconfig.get(value)));
                binding.tvconfig.setText(allconfig.get(value).get(0).configname + ">");
            }
        });

        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);


        window.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {


            }
        });
        window.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }
}


